package com.xiaoq.matrix.activity.service.impl;

import com.xiaoq.ESIndexNameProperties;
import com.xiaoq.coms.util.JsonUtil;
import com.xiaoq.matrix.activity.entity.ActivityEntity;
import com.xiaoq.matrix.activity.repository.IActivityRepository;
import com.xiaoq.matrix.activity.service.IActivityService;
import com.xiaoq.vo.PagingVo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ActivityServiceImpl implements IActivityService {

	@Autowired
	private IActivityRepository acitivityRep;

    @Autowired
    private ElasticsearchTemplate template;

    @Autowired
    private ESIndexNameProperties indexNameProperties;

	private Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);
	
	@Override
	public boolean addActivity(ActivityEntity activity) {
		
		return acitivityRep.addActivity(activity);
	}

	@Override
	public boolean delActivity(String activityId) {
		
		return acitivityRep.delActivity(activityId);
	}

	@Override
	public boolean updateActivityStatus(String id) {
		
		return acitivityRep.updateActivityStatus(id);
	}

	@Override
	public ActivityEntity findActivity(String id) {
		
		return acitivityRep.findActivity(id);
	}

	@Override
	public List<ActivityEntity> findActivityListByOrgnizer(String orgnizerId, String title, Long pubStart, Long pubEnd,
			String authStatus,PagingVo pvo) {
		
		return acitivityRep.findActivityListByOrgnizer(orgnizerId, title, pubStart, pubEnd,authStatus,pvo);
	}

	@Override
	public List<ActivityEntity> findActivityListByCity(String cityCode, PagingVo pvo) {
		List<ActivityEntity> activityList = acitivityRep.findActivityListByCity(cityCode, pvo);
		int updateTag = 0;
		if(activityList!=null){
			for(ActivityEntity activity:activityList){
				Long endTime = 0L;
				endTime = activity.getEndTime();
				String id = activity.getId();
				Long currentTime = System.currentTimeMillis();
				if(currentTime>=endTime){
					acitivityRep.updateActivityStatus(id);
					updateTag = 1;
				}
			}
		}
		// 在查询的时候将所有已过期的活动置成已经过期
		if(updateTag!=1){
			activityList = acitivityRep.findActivityListByCity(cityCode, pvo);
		}
		return activityList;
	}

	@Override
	public boolean updateActivity(ActivityEntity activity) {
		
		return acitivityRep.updateActivity(activity);
	}

	@Override
	public ActivityEntity findActivity2C(String id) {
		return acitivityRep.findActivity2C(id);
	}

	@Override
	public List<ActivityEntity> findActivityListByCity2C(String cityCode,String district, PagingVo pvo) {
		List<ActivityEntity> activityList = acitivityRep.findActivityListByCity2C(cityCode,district, pvo);
		int updateTag = 0;
		if(activityList!=null){
			for(ActivityEntity activity:activityList){
				Long endTime = 0L;
				endTime = activity.getEndTime();
				String id = activity.getId();
				Long currentTime = System.currentTimeMillis();
				if(currentTime>=endTime){
					acitivityRep.updateActivityStatus(id);
					updateTag = 1;
				}
			}
		}
		// 在查询的时候将所有已过期的活动置成已经过期
		if(updateTag!=1){
			activityList = acitivityRep.findActivityListByCity2C(cityCode,district, pvo);
		}
		return activityList;
	}

	@Override
	public List<ActivityEntity> findActivityFromEsByTitle(String orgnizerId, String title, PagingVo pv) {
		List<ActivityEntity> resultList = new ArrayList<>();
        Pageable pageable = null;
        if(pv != null){
            pageable = new PageRequest(pv.getPn(), pv.getPs());
        }

        BoolQueryBuilder builder =  QueryBuilders.boolQuery().must(QueryBuilders.termQuery("orgnizerId", orgnizerId))
                .must(QueryBuilders.queryStringQuery(title).defaultField("title").analyzer("ik_smart"))
                .must(QueryBuilders.termQuery("authStatus", "20"));

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(builder)
                .withIndices(indexNameProperties.getSitesIndexName())
                .withTypes("activity")
                .withPageable(pageable)
                .build();

        template.queryForPage(searchQuery, ActivityEntity.class, new SearchResultMapper() {
			@Override
			public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
				SearchHit[] searchHits = response.getHits().getHits();
				if(searchHits==null || searchHits.length<1){
					return null;
				}

				for (SearchHit searchHit : response.getHits()) {
					String source = searchHit.getSourceAsString();
					try {
						ActivityEntity activityEntity = JsonUtil.asObject(source, ActivityEntity.class);
						activityEntity.setId(searchHit.getId());
						resultList.add(activityEntity);
					}catch (Exception e){
						logger.error(e.getMessage(), e);
					}
				}
				return null;
			}
		});

        return resultList;
	}
}
